<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class user extends CI_Controller {
	var $data = array();
	public function __construct() {
        parent::__construct();
        if (!$this->session->userdata('username')) {
            redirect('login');
		}
        $this->data['sidebarhome']="";
	    $this->data['sidebardaftar']="";
	    $this->data['sidebardaftarclient']="";
	    $this->data['sidebardaftarfinance']="";
    	$this->data['sidebarinputdata']="";
    	
    	$this->data['sidebarcustomer']="";
    	$this->data['sidebarcabang']="";
    	$this->data['sidebaruser']="";

    	$this->load->model('mkaryawan');    
    }

	public function index() {
		//if (!$this->muser->has_access_to('user/index')) { redirect('home');return; }
		//$html['title'] = $this->mutil->get_menu_name('user/index');
		$this->data['queryuser'] = $this->muser->get_user_list();
		//$html['data_role_map'] = $this->mutil->get_table_map('tr_role');
		//$html['data_status_map'] = $this->mutil->get_status_map();
		//$html['data_status_icon_map'] = $this->mutil->get_status_icon_map();
		//$html['has_access'] = $this->muser->has_access_to('user/add');
		$this->load->view('vlistuser', $this->data);
	}
	
	public function add($username='') {
		if (!$this->muser->has_access_to(__CLASS__.'/'.__FUNCTION__)) { redirect('chart');return; }
		if (strlen($username)>0) {
			if (!ctype_alnum($username)) { redirect('chart');return; }
			if (strtolower($username)==strtolower($this->session->userdata('username'))) { redirect('chart');return; }
			$html['row'] = $this->muser->get_user($username);
			if (is_null($html['row'])) { redirect('chart');return; }
			$html['username_edited'] = $username;
		}
		$html['subtitle'] = $this->mutil->get_menu_name('user/add/'); // yg lainnya pake title, ini subtitle karena bentuknya form
		$html['random_password'] = $this->common->my_rand_number(MIN_LENGTH_PASSWORD);
		$html['arr_role'] = $this->muser->get_combo_role();
		$this->load->view('vuser_add', $html);
	}
	
	public function doadd() { // via AJAX
		if (!$this->muser->has_access_to('user/add')) { redirect('chart');return; }
		
		$data = array();
		$error = array();
		$username_edited = $this->common->filter($this->input->post('username_edited'));
		if (strlen($username_edited)>0 && !ctype_alnum($username_edited)) die('Invalid username');
		
		$post = array(
			'username'=>'Username',
			'password'=>'Password',
			'ref_role'=>'Role',
			'nama'=>'Nama',
			'nip'=>'NIP',
			'sbu' => 'sbu',
			'guid' => 'guid',
			'email'=>'Email'
		);
		
		foreach ($post as $key=>$val) {
			$input = $this->common->filter($this->input->post($key));
			if (strlen($username_edited)==0) { // add
				if (strlen($input)==0)
					$error[] = 'Anda harus mengisi '.$val;
			} else { // edit
				if (strlen($input)==0 && !in_array($key, array('username','password')))
					$error[] = 'Anda harus mengisi '.$val;
			}
			$data[$key] = $input;
		}
		
		if (count($error)==0) {
			if (strlen($username_edited)==0) { // add
				if (!ctype_alnum($data['username'])) {
					$error[] = 'Username harus karakter alfanumerik';
				} else {
					$test = $this->muser->get_user($data['username']);
					if (!is_null($test))
						$error[] = 'Username '.$data['username'].' sudah terdaftar';
				}
				if (strlen($data['password']) < MIN_LENGTH_PASSWORD)
					$error[] = 'Panjang password minimum '.MIN_LENGTH_PASSWORD.' karakter';
				$bool_nip = strlen($data['nip'])>0;
				$bool_email = strlen($data['email'])>0;
			} else { // edit
				unset($data['username']);
				$test = $this->muser->get_user($username_edited);
				if (is_null($test)) die('Invalid username');
				if (strlen($data['password']) > 0 && strlen($data['password']) < MIN_LENGTH_PASSWORD)
					$error[] = 'Panjang password minimum '.MIN_LENGTH_PASSWORD.' karakter';
				if (strlen($data['password']) == 0)
					unset($data['password']);
				$bool_nip = strlen($data['nip'])>0 && $data['nip']!=$test->nip;
				$bool_email = strlen($data['email'])>0 && $data['email']!=$test->email;
			}
			
			if ($bool_nip) {
				$arr = $this->muser->get_nip($data['nip']);
				if (count($arr)>0)
					$error[] = 'NIP '.$data['nip'].' sudah terdaftar';
			}
			if ($bool_email) {
				if (!$this->common->is_valid_email($data['email']))
					$error[] = 'Email '.$data['email'].' tidak valid';
				else {
					$arr = $this->muser->get_email($data['email']);
					if (count($arr)>0)
						$error[] = 'Email '.$data['email'].' sudah terdaftar';
				}
			}
		}
		
		if (count($error)>0) {
			echo implode('<br />', $error);
			return;
		}
		if (isset($data['password']) && strlen($data['password'])>0) // karena jika kasus edit dan password dikosongkan maka tidak perlu ada encrypt password
			$data['password'] = $this->muser->my_md5($data['password']);
		echo $this->muser->add($data, $username_edited);
	}
	
	public function role() {
		if (!$this->muser->has_access_to(__CLASS__.'/'.__FUNCTION__)) { redirect('chart');return; }
		$html['title'] = $this->mutil->get_menu_name('user/role/');
		$html['data_role'] = $this->muser->get_role_list();
		$this->load->view('vuser_role', $html);
	}
	
	public function doaddrole() {
		if (!$this->muser->has_access_to('user/addrole')) { redirect('chart');return; }
		
		$error = array();
		
		$role = $this->input->post('ROLE');
		if (strlen($role)==0)
			$error[] = 'Anda harus mengisi nama role';
		elseif ($this->muser->is_role_name_exist($role))
			$error[] = 'Role '.$role.' sudah terdaftar';
		
		if (count($error)>0) {
			echo implode('<br />', $error);
			return;
		}
		echo $this->muser->add_role($role);
	}
	
	public function doeditrolename() {
		if (!$this->muser->has_access_to('user/rolename')) { redirect('chart');return; }
		
		$role_id = $this->input->post('id');
		$role_name = $this->input->post('detil');
		if (strlen($role_name)==0) {
			echo $this->session->set_userdata('form_error', 'Nama role harus diisi');
			return '';
		}
		echo $this->muser->edit_role_name($role_id, $role_name);
	}
	
	public function roleaccess($role_id='') {
		if (!$this->muser->has_access_to(__CLASS__.'/'.__FUNCTION__)) { redirect('chart');return; }
		if (strlen($role_id)==0 || !ctype_digit($role_id)) {
			redirect('chart');
			return;
		}
		if ($role_id==$this->session->userdata('role')) {
			redirect('chart');
			return;
		}
		$role_prop = $this->muser->get_role($role_id);
		if (count($role_prop)==0) {
			redirect('chart');
			return;
		}
		$html['title'] = $this->mutil->get_menu_name('user/role/').' '.$role_prop['detil'];
		$html['arr_menu'] = $this->muser->get_authorized_url($role_id);
		$html['data_menu'] = $this->mutil->get_menu_list();
		$html['role_id'] = $role_id;
		$html['role_name'] = $role_prop['detil'];
		$this->load->view('vuser_role_access', $html);
	}
	
	public function dodeleterole() {
		if (!$this->muser->has_access_to(__CLASS__.'/'.__FUNCTION__)) { redirect('chart');return; }
		
		$role_id = $this->input->post('id');
		$role_name = $this->input->post('detil');
		if (!ctype_digit($role_id)) die();
		echo $this->muser->delete_role($role_id, $role_name);
	}
	
	// input: menu_1,menu_3,menu_5, ..........
	public function doeditroleaccess() { // via AJAX
		if (!$this->muser->has_access_to('user/roleaccess')) { redirect('chart');return; }
		
		$role_id = $this->input->post('role_id');
		$role_name = $this->input->post('role_name');
		
		if ($role_id==$this->session->userdata('role'))
			die('Unauthorized access');
		
		$str = $this->input->post('str');
		$arr_menu = explode(',', $str);
		$arr_menu_id = array();
		foreach ($arr_menu as $val) {
			if (strlen($val)>0) {
				// misal: menu_9
				$arr_temp = explode('_', $val);
				if (count($arr_temp)==2) {
					$arr_menu_id[] = $arr_temp[1];
				}
			}
		}
		echo $this->muser->edit_role_access($role_id, $role_name, $arr_menu_id);
	}
	
	public function dodelete() { // via AJAX
		if (!$this->muser->has_access_to('user/delete')) { redirect('chart');return; }
		$username = $this->common->filter($this->input->post('username'));
		if (strtolower($username)==strtolower($this->session->userdata('username'))) die('Unauthorized access');
		echo $this->muser->delete($username);
	}
	
	public function password() {
        if ($this->input->is_ajax_request() && isset($_POST['oldpass'])) {
			$error = array();
            if (strlen($this->input->post('oldpass')) == 0)
                $error[] = 'Anda harus mengisi password lama';
            else {
                $user = $this->muser->get_user($this->session->userdata('username'));
                if ($this->muser->my_md5($this->input->post('oldpass')) != $user->password)
                    $error[] = 'Password lama salah';
            }
            if (strlen($this->input->post('newpass1')) < MIN_LENGTH_PASSWORD)
                $error[] = 'Password minimum '.MIN_LENGTH_PASSWORD.' karakter';
            if (strlen($this->input->post('newpass2')) == 0)
                $error[] = 'Anda harus mengisi konfirmasi password baru';
            if ($this->input->post('newpass1') != $this->input->post('newpass2'))
                $error[] = 'Password Baru tidak sama dengan Konfirmasi Password Baru';

            if (count($error) > 0) {
                echo implode('<br />', $error);
            } else {
                $data = array(
                    'password' => $this->muser->my_md5($this->input->post('newpass1'))
                );
                echo $this->muser->change_password($data, $this->session->userdata('username'));
            }
        } else {
            $this->load->view('vpassword');
        }
    }
    
    /* Baru */
    public function gantipassword()
    {
    	if($this->session->userdata('role') == 1)
    	{
    		$this->data['username'] = $username = $this->uri->segment(3);
	    	$this->load->view('vgantipassword',$this->data);
		}
		else
			redirect('');
	}	

    public function fgantipassword()
    {
    	$username = $this->uri->segment(3);
    	$password = $this->mkaryawan->getpassword($username)->result();
    	$password_input = $this->muser->my_md5($this->input->post('password_lama'));
    	//echo $password_input; 
    	//bypass if($password[0]->password == $password_input)
    	if(true)
    	{
    		 $data123 = array(
				'username' => $username,
				'password' =>  $this->muser->my_md5($this->input->post('password')),
			);
			$this->mkaryawan->gantipassword($data123);
			return true;
    	}
    	else
    		return false;
	}	

    public function tambahuser()
    {
	    $this->data['queryprovinsi'] = $this->mkaryawan->fgetallprovinsi();
	    $this->data['querycabang'] = $this->mkaryawan->fgetallkota();
    	$this->data['querycustomer'] = $this->mkaryawan->fgetallcustomer();
    	$this->data['queryrole'] = $this->mkaryawan->getallrole();
    	$this->load->view('vtambahuser',$this->data);
	}	

	public function dotambahuser()
	{
    	$data123 = array(
			'username' => $this->input->post('username'),
			'ref_role' => $this->input->post('ref_role'),
			'id_provinsi' => $this->input->post('id_provinsi'),
			'id_kota' => $this->input->post('id_kota'),
			'id_customer' => $this->input->post('id_customer'),
			'password' =>  $this->muser->my_md5($this->input->post('password')),
		);
		$this->mkaryawan->mtambahuser($data123);
	}	
    
    public function doresetpassword()
    {
    	$data123 = array(
			'username' => $this->input->post('username'),
			'password' =>  $this->muser->my_md5('abc'),
		);
		$this->mkaryawan->gantipassword($data123);
    }
    public function set_usr4psschange()
    {
    	$this->session->set_userdata('user4passchange', $this->input->post('user4passchange'));
    }
    public function get_kabupatenkota($id){
    	$tmp     = '';
    	$data     = $this->mkaryawan->get_kabupatenkota_data($id);
    	if(!empty($data)) {
        	$tmp =    "<option value='0'>Pilih Cabang ...</option>";    
        	foreach($data as $row){    
            	$tmp .= "<option value='".$row->id_kota."'>".$row->nama_kota."</option>";
        	}
    	} else {
        	$tmp .=    "<option value='0'>Pilih Cabang ...</option>";    
    	}
    	die($tmp);
    }
}
